<?php
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/assets/tool/uploadify/uploadify.css');
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/assets/tool/uploadify/jquery.uploadify.js',CClientScript::POS_BEGIN);

$bool_IE     = false;

if( strpos( $_SERVER["HTTP_USER_AGENT"], "MSIE" ) !== false ) $bool_IE = true;
?>

<div class="tab_menu" style="position: relative;bottom: -8px;*bottom: -28px;">
    <div class="tab_control" onclick="load_page('<?=$this->createAbsoluteUrl('images/index')?>');"> Quản Lý </div>
    <div class="tab_control tab_selected"> Thêm Mới </div>
</div>
<div class="clear"></div>
<div class="box" style="float: left;">
    <form class="form_input" action="" method="post" id="form_item" name="form_item">
        <fieldset class="border_radius_all">
            <legend></legend>

            <div class="form_input_row">
                <label class="label_title">Danh Mục Ảnh:</label>
                <select
                    id          = "sl_type"
                    name        = "sl_type"
                    title       = "Danh Mục Ảnh"
                    tabindex    = "2"
                    <?php
                    if ($bool_IE != true)
                        echo "class = 'form_combobox select_css3 select_two_arrown'";
                    else
                        echo "class = 'form_combobox'";
                    ?>
                >
                    <?php 
                    foreach ($arr_library as $index => $o_library)
                        if ( ($o_library instanceof Library) == true )
                        {
                    ?>
                        <option value="<?=$o_library->key;?>"> <?=$o_library->name;?> </option>
                    <?php }?>
                </select>
            </div><!--End form_input_row -->

            <div class="form_input_row">
                <label class="label_title"> </label>

                <div class="input_items_horizon" id="div_imageUpload">
                    <input
                        id            = "txt_image"
                        name        = "txt_image"
                        title        = "Hình ảnh đại diện danh mục"
                        type        = "text"
                        class        = "form_textbox textbox_css3"
                        tabindex    = "3"
                        style        = "width: 99%;"
                    />
                    <input 
                        type    = "file"
                        id        = "file_image"
                        name    = "file_image"
                        class    = "form_textbox textbox_css3" 
                        style    = "width: 99%;"
                        accept    = "image/*" 
                        multiple= "true"
                    />
                    <br/>
                    <input
                        type    = "checkbox"
                        id        = "chk_image"
                        name    = "chk_image"
                        tabindex= "4"
                        onchange= "visible_uploadbox();"
                    /> Upload hình lên máy chủ.
                </div>
            </div><!--End form_input_row-->

            <div class="form_input_row" style="border: none;">
                <div class="input_items_horizon">
                    <input
                        title       = "Thêm Hình"
                        name        = "btn_addImage"
                        id          = "btn_addImage"
                        type        = "button"
                        value       = "Thêm Hình"
                        class       = "input_button button_css3"
                        tabindex    = "5"
                    />
                </div><!--End input_items_horizon-->
            </div><!--End form_input_row button-->
        </fieldset>
    </form>
    <div class="clear"></div>

    <div class="box_content_no_border" id="div_contentBox" style="float:left;width: 99.5%;">
        <div class="galleries_item border_box" id="div_galleriesImage">
            <div class="form_header">
                <form id = "form_item">
                <input
                    title       = "save"
                    name        = "btn_saveImage"
                    id          = "btn_saveImage"
                    type        = "button"
                    value       = "Lưu Hình"
                    class       = "button button_css3"
                    tabindex    = "5"
                />
                </form>
            </div>
            <div class="clear"></div>
        </div><!-- End galleries_item -->
    </div><!--End box_content_no_border-->

</div><!--End box-->
<script type="text/javascript">
var i_imgCount = 0;

$(document).ready(function ()
{
    $("#btn_addImage").click(function () 
    {
        if( $("select#sl_type").val()== "" )
        {
            alert("Bạn chưa chọn mục hình muốn upload.");
            $("input#sl_type").focus();
            return;
        }

        if( $("input#txt_image").val()== "" )
        {
            alert("Đường dẫn hình ảnh không được để trống.");
            $("input#txt_image").focus();
            return;
        }

        var i_indexChar   = $("input#txt_image").val().lastIndexOf("/");
        var s_imageName   = $("input#txt_image").val().substr( i_indexChar+1, $("input#txt_image").val().length);
        
        add_ImageToPrepareArea($("input#txt_image").val(), s_imageName, 1);
    });

    $("#file_image").uploadify({
        "formData" : {
            "timestamp"    : "<?=time();?>",
            "token"        : "<?=md5('unique_salt'.time());?>",
            "sl_type"      : $("select#sl_type").val(),
        },
        "buttonClass"      : "input_button button_css3",
        "swf"              : "<?=Yii::app()->baseUrl.'/assets/tool/uploadify/';?>uploadify.swf",
        "uploader"         : "<?=Yii::app()->createUrl("images/UploadImage");?>",
        "onUploadStart"    : function(file)
        {
            if( $("select#sl_type").val()=="") {
                alert("Bạn chưa chọn mục hình muốn upload.");
                $("#file_image").uploadify("cancel","*");
            }
        },//End onUploadStart
        "onUploadSuccess"  : function(file, data, response)
        {
            if( response == true )
            {
                var arr_result = $.parseJSON(data);
        
                if(arr_result.error != null){
                    alert(arr_result.error);
                    return;
                }
        
                var s_urlImage    = "<?=Yii::app()->baseUrl;?>/"+arr_result.result;
                var i_indexChar   = s_urlImage.lastIndexOf("/");
                var s_imageName   = s_urlImage.substr( i_indexChar+1, s_urlImage.length);
                add_ImageToPrepareArea(s_urlImage, s_imageName, 2);
            }//End if
        }//End onUploadSuccess
    });

    $("#file_image").hide();
});

/* ==================================================
* @Method:    add_ImageToPrepareArea
* @Describe:  Add selected image to prepare area
*             to user check last time and add these images to server
* @return:    void
* =================================================== */
function add_ImageToPrepareArea (s_imageURL, s_imageName, i_methodUpload)
{
    i_imgCount += 1;

    var ct  = '<div class = "item_vertical" id="div_img'+ i_imgCount +'">';
    ct     += '<img name="img_upload" alt = "'+ s_imageName +'" src = "'+ s_imageURL +'" />';
    ct     += '<div class="item_content border_radius_all">';
    ct     += '<span class="item_title">Mục: '+$("select#sl_type").val();
    ct     += '<input id="btn_delete" name="delete" type="button" value="Xóa" style="width:100%;" class="button button_css3" onclick="delete_selectedItem(\'div_img'+ i_imgCount +'\', '+ i_methodUpload +')">';
    ct     += '</span>';
    ct     += '</div>';
    ct     += '</div><!-- End item_vertical -->';

    $("div#div_galleriesImage").append(ct);
}//End add_ImageToPrepareArea

/* ==================================================
* @Method:    visible_uploadbox
* @Describe:  display upload image to server or
*             images from another server
* @return:    void
* =================================================== */
function visible_uploadbox()
{
    if(document.getElementById("chk_image").checked == true)
    {
        $("#txt_image").hide();
        $("#btn_addImage").hide();

        $("#file_image").show();
    }
    else
    {
        $("#txt_image").show();
        $("#btn_addImage").show();

        $("#file_image").hide();
    }
}//End visible_uploadbox

/* ==================================================
* @Method:    $("input#btn_saveImage").click
* @Describe:  save selected images to website
* @return:    void
* =================================================== */
$("input#btn_saveImage").click(function()
{
    var arr_imgUrls = $("img[name='img_upload']").map(function() {
        return this.src;
    }).get();

    var arr_imgNames = $("img[name='img_upload']").map(function() {
        return this.alt;
    }).get();

    $.ajax({
        url            : "<?=Yii::app()->createUrl("images/save")?>",
        type           : "POST",
        contentType    : "application/x-www-form-urlencoded; charset=UTF-8",
        cache          : false,
        data           : {
            sl_type        : $("select#sl_type").val(),
            arr_imgUrl     : arr_imgUrls,
            arr_imgName    : arr_imgNames
        },
        success    : function(string)
        {
            /**
             * Kiểu mặc định trả về là dạng String, bạn dùng hàm parseJSON để phân tích dữ liệu trả về
             * có 2 cách parse JSON là : JSON.parse() và $.parseJSON();
             * 1. var getData = JSON.parse(string);
             * 2. var getData = $.parseJSON(string);
            **/
            var arr_result = $.parseJSON(string);
            if(arr_result.error != null){
                alert(arr_result.error);
                $("#dialog_excute").dialog( "close" );
                return;
            }
    
            alert("Thêm Thành Công");
            load_page('<?=Yii::app()->createUrl("images/index")?>');
        },
        error: function (){
            alert('Trang hiện hành không tồn tại.');
        }
    });//End Ajax
});//End form submit

/* ==================================================
 * @Method:    $("input#btn_saveImage").click
 * @Describe:  save selected images to website
 * @return:    boolean
 * =============================================== */
function delete_selectedItem(s_idDiv, i_uploadMethod)
{
    if ( s_idDiv == "" )
    {
        alert("This image don't have file name to remove, please refresh and add image again.");
        return false;
    }
    else if ( s_idDiv != "" && i_uploadMethod == 1 )
    {
        //Upload images from another server
        $("div#"+s_idDiv).remove();
    }
    else if ( s_idDiv != "" && i_uploadMethod == 2 )
    {
        $.ajax({
            url         : "<?=Yii::app()->createUrl("images/DeleteFile")?>",
            type        : "POST",
            contentType : "application/x-www-form-urlencoded; charset=UTF-8",
            cache       : false,
            data        : {
                s_imgName    : $("div#"+s_idDiv).children().attr("alt"),
                sl_type      : $("select#sl_type").val()
            },
            success     : function(string){ if(string==1) $("div#"+s_idDiv).remove();},
            error       : function (){alert('Trang hiện hành không tồn tại.');}
        });//End Ajax
    }//End else if

    return true;
}
</script>